package com.iqiyi.game.ams.domain.acitivty.entity;

import com.iqiyi.game.ams.domain.acitivty.entity.module.User;
import com.iqiyi.game.ams.domain.core.entity.Entity;
import com.iqiyi.game.ams.infrastructure.app.AppException;
import com.iqiyi.game.ams.ui.dto.ActivityDTO;
import com.iqiyi.game.ams.ui.dto.UserDTO;
import com.iqiyi.game.ams.ui.query.ActivityQuery;
import com.iqiyi.game.ams.ui.query.ModuleQuery;
import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hanbaoyu
 */
@Data
public class Activity implements Entity {
    private Integer id;
    private String name;
    private LocalDateTime startAt;
    private LocalDateTime endAt;
    private LocalDateTime offlineAt;

    private Map<String, Module> moduleMap = new HashMap<>();

    private User user;

    public void getModules(ModuleQuery moduleQuery) {
        if (moduleQuery.queryAll()) {
            this.getModuleMap().forEach((k, v) -> {
                if (v.getIsDefault()) {
                    executeModule(v);
                }
            });
            return;
        }
        // 位置todo
        if (!this.getModuleMap().containsKey(moduleQuery.getLabel())) {
            throw new AppException("label参数无效");
        }

        executeModule(this.getModuleMap().get(moduleQuery.getLabel()));
    }

    private void executeModule(Module module) {
        Object o = module.execute();
        if (o instanceof User) {
            User user = (User) o;
            this.setUser(user);
        }
    }

//    public Boolean valid() {
//        // 检查活动时间
//        LocalDateTime now = LocalDateTime.now();
//        if (startAt.isAfter(now)) {
//            throw new AppException("活动未开始");
//        }
//
//        if (endAt.isBefore(now)) {
//            throw new AppException("活动已结束");
//        }
//
//        if (offlineAt.isBefore(now)) {
//            throw new AppException("活动已下线");
//        }
//
//        return true;
//    }
//

    public ActivityDTO convert() {
        ActivityDTO activityDTO = new ActivityDTO();
        BeanUtils.copyProperties(this, activityDTO, new String[] {"moduleMap"});

        if (this.getUser() != null) {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(this.getUser(), userDTO);
            activityDTO.setUser(userDTO);
        }

        return activityDTO;
    }
}
